package br.com.async.controller.auth;

import br.com.async.controller.log.AsyncLog;
import br.com.async.controller.wizard.WizardController;
import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;


/**
 * @author rondymesquita
 *	Cria um filtro para a aplica��o
 *	Qualquer recurso apenas ser� acessado se houver um usu�rio logado em uma sess�o
 *	M�todos com @Public s�o p�blicos e n�o ser�o interceptados
 *	Qualquer outro m�todo que n�o possua @Public ser� interceptado.
 */
@Intercepts
public class AsyncInterceptor implements Interceptor {

	private Result result;
	private UserComponent userComponent;
	private AsyncLog asyncLog;
	private WizardController wizardController;
	private LoginController loginController;

	public AsyncInterceptor(Result result, UserComponent userComponent, AsyncLog asyncLog, WizardController wizardController, LoginController loginController) {
		this.result = result;
		this.userComponent = userComponent;
		this.asyncLog = asyncLog;
		this.wizardController = wizardController;
		this.loginController = loginController;
	}

	public boolean accepts(ResourceMethod method) {
		asyncLog.log(method);
		return !(method.getMethod().isAnnotationPresent(Public.class) || method.getResource().getType().isAnnotationPresent(Public.class));
	}
	
	public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance) throws InterceptionException {
		
		
		if (userComponent.isLogged()) {
			stack.next(method, resourceInstance);
		} else {
			result.redirectTo(LoginController.class).login();
		}
		
		//System.out.println("Execute" + WizardController.execute);
//		if(WizardController.execute == 0){
//			WizardController.execute++;
//			//System.out.println("Go to wizard");
//			result.redirectTo(WizardController.class).wizard();
//		}
//		else if (userComponent.isLogged()) {
//			//System.out.println("Is logged");
//			stack.next(method, resourceInstance);
//		} else {
//			//System.out.println("Not logged");
//			result.redirectTo(LoginController.class).login();
//		}

	}

}
